import React,{useState,useEffect} from 'react';
import { EllipsisOutlined, PlusOutlined,EditOutlined,DeleteOutlined ,ExclamationCircleFilled} from '@ant-design/icons';
import { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, TableDropdown } from '@ant-design/pro-components';
import { Button, Dropdown, Space, Tag ,message ,Modal} from 'antd';
import UserForm from './edit'
import { useRef } from 'react';
import request from 'umi-request';
import {userTableData} from '../../service'
import store from '@/redux/store.js'

const { confirm } = Modal;
export const waitTimePromise = async (time) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export const waitTime = async (time) => {
  await waitTimePromise(time);
};
const TableArea = (props) => {
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [update,setUpdate] = useState({})

  let tableHead = props?.tableHead || []
  let columns = []
  tableHead.forEach((item)=>{
    let obj ={
      title:item.name,
      dataIndex:item.code,
      search: item.search,
      sorter: item.isSort,
    }
    columns.push(obj)
  })
  let indexCol = {title:'排序',dataIndex: 'index',valueType: 'indexBorder',width: 48}
  let editCol ={
    title: '操作',
    valueType: 'option',
    key: 'option',
    render: (text, record, _, action) => [
      <a
        key="editable"
        onClick={() => {
          action?.startEditable?.(record.id);
          setModalVisible(true)
        }}
      >
        编辑
      </a>,
      <a key="copy" onClick={()=>{
        action?.startEditable?.(record.id);
        copyOne(record)
      }}>
        复制
      </a>,
      <a  key="delable" style={{'color':'#ff7875'}} onClick={()=>{
        action?.startEditable?.(record.id);
        handleOneRemove(record.key)
      }}>
        删除
      </a>
    ],
  }
  columns.push(editCol)
  columns.splice(0,1,indexCol)
  let tableData =  props?.userTableList || []

  const handleUpdate = (fields)=>{
    console.log('handleUpdate')
    return true;
  }
  const handleAdd = (fields)=>{
    console.log('handleAdd')
    return true;
  }
  const handleRemove =  (selectedRows) => {
    if (selectedRows.length === 0){
      message.warning('没有选中任何要数据')
      return false
    }
    // const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    let toDoId = selectedRows.map((row) => row.roleId)
    return true;
  }
  const handleOneRemove =  (id) => {
    confirm({
      title: '确定要删除此数据吗?',
      icon: <ExclamationCircleFilled />,
      okText: '是',
      okType: 'danger',
      cancelText: '否',
      onOk() {
        console.log('OK');
      },
      onCancel() {
        console.log('Cancel');
      },
    });

  }
  const copyOne=(row)=>{
    console.log('copyOne',row)
  }
  const search=(params, sorter, filter)=>{
    console.log('params',params, sorter, filter)

  }

  const actionRef = useRef();
  const state=store.getState();
  useEffect(() => {
    // store.subscribe()是redux提供的，监测store更新的函数
    store.subscribe(() => {
      // 当store数据更新后执行 setUpdate() ，组件重新加载，实现界面store数据更新
      setUpdate({})
    })
  })
  return (
    <div>
      {
        JSON.stringify(state) !== undefined && JSON.stringify(state) !== '{}' && state.CheckTree !== undefined &&
          <p>{state.CheckTree}</p>
      }
      <ProTable
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={(params, sorter, filter) =>
          userTableData().then((res) => {
            return {
              data: res?.data?.userTableList || [],
              total: res?.data?.total,
              success: true,
            };
          })
        }
        editable={{type: 'multiple',}}
        rowKey="key"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        form={{
          // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
          // syncToUrl: (values, type) => {
          //   if (type === 'get') {
          //     return {
          //       ...values,
          //       created_at: [values.startTime, values.endTime],
          //     };
          //   }
          //   return values;
          // },
        }}
        pagination={{
          pageSize: 10,
          onChange: (page) => console.log(page),
        }}
        dateFormatter="string"
        headerTitle="高级表格"
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              console.log('新建')
              setModalVisible(true)
              // actionRef.current?.reload();
            }}
            type="primary"
          >
            新建
          </Button>,
          <Button
            key="button"
            icon={<EditOutlined />}
            onClick={() => {
              console.log('编辑')
            }}
            type="primary"
          >
            编辑
          </Button>,
          <Button
            key="button"
            icon={<DeleteOutlined />}
            onClick={async () => {
              const success = await handleRemove(selectedRowsState);
              if (success) {
                setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }
            }}
            type="primary"
            danger
          >
            删除
          </Button>
        ]}
      />
      <UserForm
        open={modalVisible}
        onSubmit={async (values) => {
          let success = false;
          if (values.userId) {
            success = await handleUpdate({ ...values });
          } else {
            success = await handleAdd({ ...values });
          }
          if (success) {
            setModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setModalVisible(false);
        }}
      />
    </div>
  );
};

export default TableArea;
